package com.chengcang.admin.modules.busi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chengcang.admin.modules.busi.dao.BusiAddressDao;
import com.chengcang.admin.modules.busi.dto.BusiAddressDTO;
import com.chengcang.admin.modules.busi.entity.BusiAddressEntity;
import com.chengcang.admin.modules.busi.service.BusiAddressService;
import com.chengcang.admin.modules.security.user.SecurityUser;
import com.chengcang.common.constant.Constant;
import com.chengcang.common.exception.CustomException;
import com.chengcang.common.page.PageData;
import com.chengcang.common.service.impl.CrudServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 地区表
 *
 * @author zhanli
 * @since 1.0.0 2023-01-10
 */
@Service
public class BusiAddressServiceImpl extends CrudServiceImpl<BusiAddressDao, BusiAddressEntity, BusiAddressDTO> implements BusiAddressService {

    @Override
    public QueryWrapper<BusiAddressEntity> getWrapper(Map<String, Object> params) {
        String id = (String) params.get("id");

        QueryWrapper<BusiAddressEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);
        Long tenantId = SecurityUser.getTenantId();
        wrapper.eq(tenantId != null, "tenant_id", tenantId);
        return wrapper;
    }

    @Override
    public PageData<BusiAddressDTO> page(Map<String, Object> params) {

        IPage<BusiAddressEntity> ipage = getPage(params, Constant.CREATE_DATE, false);
        List<BusiAddressEntity> sysDeptEntities = baseDao.selectList(getWrapper(params));
        PageData<BusiAddressDTO> page = getPageData(sysDeptEntities, ipage.getTotal(), BusiAddressDTO.class);

        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setDefaultAddress(String id) {
        Long tenantId = SecurityUser.getTenantId();
        if (null == tenantId) {
            throw new CustomException("超级管理员不存在默认地址！");
        }
        LambdaQueryWrapper<BusiAddressEntity> wrapper = Wrappers.<BusiAddressEntity>lambdaQuery()
                .eq(BusiAddressEntity::getTenantId, tenantId)
                .eq(BusiAddressEntity::getDefaulted, 0);
        BusiAddressEntity oldBusiAddressDefault = baseDao.selectOne(wrapper);
        Optional.ofNullable(oldBusiAddressDefault).ifPresent(busiInvoiceHeadEntity -> {
            busiInvoiceHeadEntity.setDefaulted(1);
            baseDao.updateById(busiInvoiceHeadEntity);
        });


        BusiAddressEntity newBusiAddressDefault = baseDao.selectById(id);
        if(null == newBusiAddressDefault) {
            throw new CustomException("未查询到相关地址信息！");
        }
        newBusiAddressDefault.setDefaulted(0);
        baseDao.updateById(newBusiAddressDefault);

    }

    @Override
    public void delete(Long[] ids) {
        List<BusiAddressEntity> busiAddressEntities = baseDao.selectBatchIds(Arrays.asList(ids));
        if (busiAddressEntities.stream().map(BusiAddressEntity::getDefaulted).anyMatch(o -> o == 0)) {
            throw new CustomException("默认地址不允许删除！");
        }
        super.delete(ids);
    }
}